<script setup lang="tsx">
import { ref, reactive, unref, provide } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { ElForm, ElFormItem, ElInput, ElButton, ElDialog, ElMessage } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getListApi, withdrawApi, type Row } from '@/api/finance/accountName'
const formRef = ref<InstanceType<typeof ElForm>>()
const dialogFormVisible = ref(false)
const form = ref({
  id: '',
  name: '',
  money_withdraw: '',
  money: ''
})
const validateMoney = (rule: any, value: string, callback: (error?: Error) => void) => {
  const numValue = Number(value)
  if (isNaN(numValue)) {
    return callback(new Error('请输入有效的数字'))
  }
  if (numValue <= 0) {
    return callback(new Error('提现金额必须大于0'))
  }
  if (numValue > Number(form.value.money_withdraw)) {
    return callback(new Error(`提现金额不能大于${Number(form.value.money_withdraw)}`))
  }
  const decimalPlaces = value.split('.')[1]
  if (decimalPlaces && decimalPlaces.length > 2) {
    return callback(new Error('最多支持两位小数'))
  }
  return callback()
}

const rules = ref({
  money: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { asyncValidator: validateMoney, trigger: 'blur' }
  ]
})

defineOptions({
  name: 'AccountName'
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    type: 'selection'
  },
  {
    field: 'id',
    label: '账户编号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'name',
    label: '姓名',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'money_all',
    label: '账户总金额',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'money_withdraw',
    label: '已提现金额',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'money',
    label: '待提现金额',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const ids = ref<string[]>([])
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose } = tableMethods
let currentRow = reactive<any>({})

const Auditing = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: Row) => v.id) || ''
  if (Object.keys(ids.value).length === 0) {
    ElMessage('请选择')
    return
  } else if (Object.keys(ids.value).length >= 2) {
    ElMessage('只能选择一个')
    return
  }
  elTableExpose?.getSelectionRows().map((v: Row) => {
    form.value = {
      id: v.id,
      name: v.name,
      money_withdraw: v.money
    }
  }) || ''
  dialogFormVisible.value = true
}

const confirm = async () => {
  try {
    await formRef.value.validate()
    // 表单验证通过后执行以下代码
    const res = await withdrawApi({ deliver_driver_id: form.value.id, money: form.value.money })
    if (res) {
      ElMessage.success(res.msg)
      dialogFormVisible.value = false
      getList()
    }
  } catch (err) {
    console.log('表单验证失败:', err)
  }
}

provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap title="司机账户">
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="Auditing">提现</BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{ total }"
      @register="tableRegister"
    />
    <el-dialog v-model="dialogFormVisible" title="提现申请" width="500">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="姓名">
          <el-input v-model="form.name" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="待提现金额">
          <el-input v-model="form.money_withdraw" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="所需提现金额" prop="money">
          <el-input v-model="form.money" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </ContentWrap>
</template>
